package com.whiteape.book.ui.activity;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whiteape.book.R;

import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.CategoryDetailBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceCategoryBean;
import com.whiteape.book.model.type.SourceFromType;
import com.whiteape.book.ui.adapter.SourceCategoryAdapter;
import com.whiteape.book.ui.base.BaseActivity;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class SiteCategoryDetailActivity extends BaseActivity {

    SourceCategoryAdapter mAdapter;
    @BindView(R.id.refresh_rv_content)
    RecyclerView recyclerView;

    @BindView(R.id.refresh_layout)
    RefreshLayout refreshLayout;

    SiteSourceBean siteSourceBean;
    String siteHostUrl;
    String categoryDetailUrl;
    String categoryName;
    int page = 1;

    List<CategoryDetailBo> data = new ArrayList<>();
    private SiteSourceCategoryBean categoryBean;

    public static final String KEY_SITE_HOST = "site_source_host";
    public static final String KEY_CATEGORY_DETAIL_URL = "category_detail_url";
    public static final String KEY_CATEGORY_NAME = "category_name";
    public static final String KEY_CATEGORY = "category";

    @Override
    protected int getContentId() {
        return R.layout.activity_refresh_list;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        if (savedInstanceState != null) {
            siteHostUrl = savedInstanceState.getString(KEY_SITE_HOST);
            categoryDetailUrl = savedInstanceState.getString(KEY_CATEGORY_DETAIL_URL);
            categoryName = savedInstanceState.getString(KEY_CATEGORY_NAME);
            categoryBean = savedInstanceState.getParcelable(KEY_CATEGORY);
        }
        if (siteHostUrl == null) {
            siteHostUrl = getIntent().getStringExtra(KEY_SITE_HOST);
        }
        if (categoryDetailUrl == null) {
            categoryDetailUrl = getIntent().getStringExtra(KEY_CATEGORY_DETAIL_URL);
        }
        if (categoryName == null) {
            categoryName = getIntent().getStringExtra(KEY_CATEGORY_NAME);
        }
        if (categoryBean == null) {
            categoryBean = getIntent().getParcelableExtra(KEY_CATEGORY);
        }

        siteSourceBean = MediaStorageManager.getInstance().getSiteSourceBeanByHostUrl(siteHostUrl);
        mAdapter = new SourceCategoryAdapter(R.layout.item_category_book, data);
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(categoryName);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("page", page);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.containsKey("page")) {
            page = savedInstanceState.getInt("page");
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //TODO 为什么还要bind，命名
//        mAdapter.bindToRecyclerView(recyclerView);
//        mAdapter.disableLoadMoreIfNotFullPage();
        mAdapter.setOnLoadMoreListener(() -> {
                    if (siteSourceBean.getSourceFrom() != null &&
                            (siteSourceBean.getSourceFrom() == SourceFromType.SOURCE_FROM_YUEDU2 ||
                                    siteSourceBean.getSourceFrom() == SourceFromType.SOURCE_FROM_YUEDU3)) {
                        loadMore(categoryBean, page++, categoryDetailUrl);
                        return;
                    }
                    if (data.size() == 0 || StringUtils.isEmpty(data.get(data.size() - 1).getNextPage())) {
                        mAdapter.loadMoreEnd();
                        return;
                    }
                    loadMore(categoryBean, page++, data.get(data.size() - 1).getNextPage());
                }
                , recyclerView);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            CollectionMediaBean collectionMediaBean = new CollectionMediaBean();
            CategoryDetailBo categoryDetailBo = data.get(position);


            collectionMediaBean.setMediaType(categoryDetailBo.getMediaType());
            collectionMediaBean.setAuthor(categoryDetailBo.getAuthor());
            collectionMediaBean.setCoverUrl(categoryDetailBo.getCoverUrl());
            collectionMediaBean.setId(categoryDetailBo.getDetailUrl());
            collectionMediaBean.setCategory(categoryDetailBo.getCategory());
            collectionMediaBean.setDesc(categoryDetailBo.getDesc());
            collectionMediaBean.setLastChapter(categoryDetailBo.getLastChapter());
            collectionMediaBean.setLastUpdated(categoryDetailBo.getLastUpdated());
            collectionMediaBean.setState(categoryDetailBo.getState());
            collectionMediaBean.setTitle(categoryDetailBo.getTitle());
            collectionMediaBean.setWordCount(categoryDetailBo.getWordCount());
            collectionMediaBean.setSiteSourceBean(categoryDetailBo.getSiteSourceBean());
            collectionMediaBean.setVarMap(categoryDetailBo.getVarMap());
//                    collectionMediaBean.setBookSourceUrl();
//                    String bookId = mSearchAdapter.getItem(pos).get_id();
            MediaDetailActivity.startActivity(this, collectionMediaBean, null);
        });

        refreshLayout.setOnReloadingListener(this::startLogic);
    }

    @Override
    protected void startLogic() {
        super.startLogic();

        refreshLayout.showLoading();
        //可能有需要varmap中的page作为下一页的规则，先清空，然后从1开始
        //只能临时清空page，其他参数不能动
        if (categoryBean.getVarMap() != null) {
            categoryBean.getVarMap().remove("page");
        }
        //查看本地是否有，有的话，直接快速提取第一页的数据
        categoryBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        categoryBean.resetCategoryDetailBoList();
        List<CategoryDetailBo> singleCategoryDetailBoList = categoryBean.getCategoryDetailBoList();
        if (singleCategoryDetailBoList != null && !singleCategoryDetailBoList.isEmpty()) {
            for (CategoryDetailBo detailBo : singleCategoryDetailBoList) {
                detailBo.setSiteSourceBean(siteSourceBean);
            }
            data.addAll(singleCategoryDetailBoList);
            refreshLayout.showFinish();
            mAdapter.notifyDataSetChanged();
        } else {
            loadMore(categoryBean, page++, categoryDetailUrl);
        }

    }

    private void loadMore(SiteSourceCategoryBean categoryBean, int page, String url) {

        addDisposable(WebMediaManager.getInstance()
                .getSourceCategory(siteSourceBean, categoryBean, page, url)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(categoryBos -> {
                    if (categoryBos == null || categoryBos.isEmpty()) {
                        if (data.isEmpty()) {
                            refreshLayout.showEmpty();
                        } else {
                            mAdapter.loadMoreEnd();
                        }
                        return;
                    }
                    refreshLayout.showFinish();
                    int start = data.size();
                    data.addAll(categoryBos);
//                    mAdapter.notifyDataSetChanged();
                    mAdapter.notifyItemRangeChanged(start, categoryBos.size());
                    mAdapter.loadMoreComplete();

                }, throwable -> {
                    throwable.printStackTrace();
//                    refreshLayout.showError();
                    mAdapter.loadMoreEnd();
                    refreshLayout.showError();

                }));
    }
}
